<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 将多个promise实例包装成一个新的promise实例
        let p1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(1)
            }, 1000);
        });
        let p2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(2)
            }, 2000);
        });
        let p3 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(3)
            }, 3000);
        });

        // 调用
        const pRace = Promise.race([p1,p2,p3]);
        pRace.then(res=>console.log(res));
        pRace.catch(err=>console.log(err));

        // promise.race：只要实例中有一个先改变状态，就会把这个实例的参数返回给prace的回调函数

        // 使用场景：请求超时提示
        function request(){
            return new Promise((resolve, reject)=>{
                setTimeout(() => {
                    resolve('请求成功');
                }, 4000);
            })
        }
        function timeout(){
            return new Promise((resolve, reject)=>{
                setTimeout(() => {
                    reject('网络超时');
                }, 3000);
            })
        }

        // 因为在这个案例中，timeout的状态改变是比request要快的，所以这里的race会取timeout里的返回值
        Promise.race([request(),timeout()]).then(res=>{
            console.log(res);
        }).catch(err=>{
            console.log(err);
        })
    </script>
</body>

</html>